package logic

import (
	"context"
	"fmt"
	"wechat/models/mysql"

	"wechat/userrpc/internal/svc"
	"wechat/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RecordGiveLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRecordGiveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RecordGiveLogic {
	return &RecordGiveLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 申请列表
func (l *RecordGiveLogic) RecordGive(in *userrpc.RecordGiveRequest) (*userrpc.RecordGiveResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	mysql.DB.Where("id = ?", in.UserId).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前用户不存在")
	}

	var applyRecord mysql.ApplyRecord

	mysql.DB.Debug().Where("id = ?", in.RecordId).Find(&applyRecord)

	if applyRecord.FriendId != in.UserId {
		return nil, fmt.Errorf("当前申请记录不是你的")
	}

	if applyRecord.Status != 0 {
		return nil, fmt.Errorf("当前记录已修改其申请")
	}

	applyRecord.Status = in.Status

	mysql.DB.Debug().Updates(&applyRecord)

	friend := mysql.Friend{
		UserId:   applyRecord.FriendId,
		FriendId: applyRecord.UserId,
	}

	mysql.DB.Debug().Create(&friend)

	friends := mysql.Friend{
		FriendId: applyRecord.FriendId,
		UserId:   applyRecord.UserId,
	}

	mysql.DB.Debug().Create(&friends)

	return &userrpc.RecordGiveResponse{Id: int64(applyRecord.ID)}, nil
}
